package com.team.employment.web.admin.custom.audit;

import com.baomidou.mybatisplus.extension.service.IService;
import com.team.employment.model.enums.BaseEnum;
import com.team.employment.model.enums.EntityType;
import com.team.employment.web.admin.service.*;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Map;

/*
    动态获取不同类型的Service
 */
@Service
public class StatusAuditStrategyFactory  implements Converter<String, EntityType> {


    @Autowired
    private final ApplicationContext applicationContext; // 推荐注入而非手动创建


    @Autowired
    public StatusAuditStrategyFactory (ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }


    @Override
    public EntityType convert(String code) {
        EntityType[] entityTypes = EntityType.values();
        for (EntityType entityType : entityTypes){
            if (entityType.getCode().equals(Integer.valueOf(code))){
                return entityType;
            }
        }
        throw new IllegalArgumentException("code:"+code+"非法");
    }

    public <T> IService<T> getService(String code){
        EntityType entityType = this.convert(code);
        String serviceName = entityType.getName();
        String beanName =
                Character.toLowerCase(serviceName.charAt(0)) +
                        serviceName.substring(1) +
                        "Impl";

        if (!applicationContext.containsBean(beanName)){
            throw new NoSuchBeanDefinitionException(serviceName);
        }
        return (IService<T>) applicationContext.getBean(beanName);
    }



}
